package com.lqk.demo.concurrencytools.threadpool.juc.reentrantreadwritelock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static com.lqk.demo.n2.util.Sleeper.sleep;

/**
 * @author lqk
 * @date 2022/1/11 19:27
 *
 * 当读操作远远高于写操作时，这时候使用 读写锁 让 读-读 可以并发，提高性能。
 * 读读可以并发 读写互斥 写写互斥
 *
 * 注意事项:
 *  读锁不支持条件变量
 *  重入时升级不支持：即持有读锁的情况下去获取写锁，会导致获取写锁永久等待
 *  重入时降级支持：即持有写锁的情况下去获取读锁
 */
@Slf4j
public class TestReentrantReadWriteLock {
    public static void main(String[] args) throws InterruptedException {
        DataContainer dataContainer = new DataContainer();
        new Thread(()->{
//            dataContainer.read();
            dataContainer.write();
        },"t1").start();
        Thread.sleep(1000);
        new Thread(()->{
//            dataContainer.read();
            dataContainer.write();
        },"t2").start();
    }
}

@Slf4j
class DataContainer {
    private Object data;
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    // 读锁
    private ReentrantReadWriteLock.ReadLock r = rw.readLock();
    // 写锁
    private ReentrantReadWriteLock.WriteLock w = rw.writeLock();

    public Object read() {
        log.debug("获取读锁...");
        r.lock();
        try {
            log.debug("读取");
            sleep(1);
            return data;
        } finally {
            log.debug("释放读锁...");
            r.unlock();
        }
    }

    public void write() {
        log.debug("获取写锁...");
        w.lock();
        try {
            log.debug("写入");
            sleep(1);
        } finally {
            log.debug("释放写锁...");
            w.unlock();
        }
    }

}
